/**
  终端合同产品
  type = 1 单位价格
  type =2  无单位价格
  type = 4 仪器合同产品
  经销商合同产品
  type = 3 经销商合同产品
*/
public without sharing class ContractProductPDFController {

	public String conId ;//合同的id

	public List<List<ContractProductBean>> cpbList {get;private set;}//合同产品

	public Integer pageCnt {get;set;}//页数

  public String  type {get;set;}//类型

  public String title {get;set;}//标题

	public Contract__c con {get;private set;}//合同
    public ContractProductPDFController() {
         conId = System.currentPageReference().getParameters().get('conid');
         type = System.currentPageReference().getParameters().get('type');
         Boolean isDealer = (type == '3' || type == '2') ? true : false;

        title = System.currentPageReference().getParameters().get('title');


         con = [select Id,Name ,Maccura__r.Name ,Account__r.Name,ContractNo__c,Year__c from Contract__c where Id =:conId];
        cpbList = new List<List<ContractProductBean>>();
        Integer idx = 0;

        String sql = 'select Id, ReagentProducts__c,Price__c, ReagentProducts__r.NCvpzwh__c,ReagentProducts__r.Vmakefactory__c,ReagentProducts__r.Brand__c,Contract__r.Name,ReagentProducts__r.SerialNo__c,ReagentProducts__r.zl__c,ReagentProducts__r.Spec__c,ReagentProducts__r.Unit__c,ReagentProducts__r.Name ,ReagentProducts__r.Model__c from ContractReagentInformation__c where Contract__c =\''+conId+'\'';
         // if(type == '4'){
         //    sql += ' and ReagentProducts__r.Category0__c = \'仪器\''; 

         // } else{
         //    sql += ' and ReagentProducts__r.Category0__c != \'仪器\''; 
         // }    
        /*List<ContractProductBean>  tmp1 = new List<ContractProductBean>();

         for (Integer i = 0; i < 50  ;i++ ) {
           tmp1.add(new ContractProductBean(i));
         }
         cpbList.add(tmp1);*/
            //726pt  748pt
        List<ContractReagentInformation__c> cpList =  Database.query(sql);
        Set<Id>  pset= new Set<Id>();
        for (ContractReagentInformation__c cp:cpList) {
          pset.add(cp.ReagentProducts__c);
        }
        System.debug(pset);
        System.debug( con.Maccura__r.Name);
        Map<Id,Price__c> priceMap = ImportObject.getPriceMap(pset, con.Maccura__r.Name );
        System.debug(priceMap);
        List<ContractProductBean>  temp = new List<ContractProductBean>();
        Integer rows = 0;
        Decimal totalrowHeight = 0;

        for (ContractReagentInformation__c cp :cpList) {
          		//for (Integer i = 0; i < 10 ; i ++ ) {
                Decimal  h1 = 0;
                Decimal  h2 = 0;
                Decimal h3 = 0;
                if(cp.ReagentProducts__r.Spec__c != null )  h1  = Math.ceil(cp.ReagentProducts__r.Spec__c.length() / 8.0);
                if(cp.ReagentProducts__r.Name != null ) h2 = Math.ceil(cp.ReagentProducts__r.Name.length() / (isDealer == true ? 16.0 : 27.0));
                if(cp.ReagentProducts__r.Model__c != null ) h3 = Math.ceil(cp.ReagentProducts__r.Model__c.length() / 8.0);
                if(cp.ReagentProducts__r.Vmakefactory__c != null  && type == '2') h3 = h3  <  Math.ceil(cp.ReagentProducts__r.Vmakefactory__c.length() / 10.0) ? Math.ceil(cp.ReagentProducts__r.Vmakefactory__c.length() / 10.0) : h3  ;
                if(cp.ReagentProducts__r.NCvpzwh__c != null  && type == '2') h3 = h3  <  Math.ceil(cp.ReagentProducts__r.NCvpzwh__c.length() / 8.0) ? Math.ceil(cp.ReagentProducts__r.NCvpzwh__c.length() / 8.0) : h3  ;

                 Decimal h = 0 ;
                h  =  h1 > h2  ? h1 : h2 ;
                h = h > h3 ? h : h3 ;

                Integer nowRows = rows ;
                rows += h > 2 ? Integer.valueOf(h) : 2 ;
                Decimal  rowHeight = h > 2 ? 22 +12*(h -2) : 22 ;
                totalrowHeight += rowHeight;
                temp.add(new ContractProductBean(cp,priceMap.get(cp.ReagentProducts__c),idx+1,isDealer,rowHeight));
                if((cpbList.size() == 0 && totalrowHeight > 704 )|| totalrowHeight > 726){
                    Decimal maxH = cpbList.size() == 0 ? 712 : 728;
                    List<ContractProductBean> t = new List<ContractProductBean>();
                    Decimal yHeight = 0;
                    if(totalrowHeight > maxH){

                      while(totalrowHeight > maxH){
                        ContractProductBean rm = temp.get(temp.size() -1);

                        totalrowHeight -= rm.rowHeight;
                        yHeight += rm.rowHeight;
                        t.add(rm);
                        temp.remove(temp.size() -1);
                      }



                    }
                    List<ContractProductBean> t2 = new List<ContractProductBean>();
                          t2.addAll(temp);
                          cpbList.add(t2);
                          temp.clear();
                          temp.addAll(t);
                          totalrowHeight = yHeight;



                }
                /*
                if( (cpbList.size() == 0 && totalrowHeight < 694)|| totalrowHeight < 726)temp.add(new ContractProductBean(cp,idx+1,isDealer,rowHeight));
                if( (cpbList.size() == 0  && totalrowHeight >= 694 && totalrowHeight < 704  )||( totalrowHeight >= 716 && totalrowHeight < 726)){
                  System.debug('===>'+totalrowHeight);
                    List<ContractProductBean> t = new List<ContractProductBean>();
                          t.addAll(temp);
                          cpbList.add(t);
                          temp.clear();
                          totalrowHeight = 0;
                }else if( (cpbList.size() == 0&& totalrowHeight >= 694)|| totalrowHeight >= 726 ){
                  List<ContractProductBean> t = new List<ContractProductBean>();
                  System.debug('===>'+totalrowHeight);
                           t.addAll(temp);
                          cpbList.add(t);
                          temp.clear();
                          totalrowHeight = 0;
                  temp.add(new ContractProductBean(cp,idx+1,isDealer,rowHeight));

                }*/
              /*if((cpbList.size() == 0 && rows >= 60 && nowRows <= 60  ) ||  (rows >= 64 && nowRows <= 64) ){
                          List<ContractProductBean> t = new List<ContractProductBean>();
                          t.addAll(temp);
                          cpbList.add(t);
                          temp.clear();
                        rows =  cpbList.size() == 1 ? rows - 60 : rows - 64 ;
                }  */        
              
              idx ++; 
             // }
            
        	
        }
        if(temp.size() >0)cpbList.add(temp);
        pageCnt = cpbList.size();
    }


    public PageReference jump (){

      PageReference ref = new PageReference('/apex/ContractProductPDF?id=' +conId+'&type=1');
      ref.setRedirect(true);
       return ref;

    }
    public class ContractProductBean{

    	public String index {get;set;}//序号
    	public String productName {get;set;}//合同名称
    	public String brand {get;set;}//品牌
    	public String serialNo {get;set;}//存货代码
    	public String spec {get;set;}//规格
    	public String unit {get;set;}//单位
    	public Decimal price {get;set;}//价格(含税)
      public Decimal zl {get;set;}//装量
    	public Decimal eprice {get;set;}//单位价
      public Decimal unitprice {get;set;}//市场报价
      public Integer taxrate {get;set;}//税率
      public Decimal notaxprice {get;set;}//价格(不含税)
      public String model {get;set;}//型号
      public Decimal rowHeight {get;set;}//行高
      public String num {get;set;}//数量
      public String vmk {get;set;}//生产企业
      public String pzwh {get;set;}//批准文号

      /*public ContractProductBean(Integer idx ){
        index = String.valueOf(idx);
        rowHeight = 22.0;

      }*/
    	public ContractProductBean(ContractReagentInformation__c cp,Price__c pr ,Integer idx,Boolean isDealer,Decimal rowh ){
    		index = String.valueOf(idx);
    		productName = isDealer == true ? autoNextLine(cp.ReagentProducts__r.Name,16): autoNextLine(cp.ReagentProducts__r.Name,27);
    		brand = autoNextLine(cp.ReagentProducts__r.Brand__c,5);
    		serialNo = cp.ReagentProducts__r.SerialNo__c ;//autoNextLine(cp.ReagentProducts__r.SerialNo__c,8);
    		spec = autoNextLine(cp.ReagentProducts__r.Spec__c,8);
    		unit = cp.ReagentProducts__r.Unit__c;
    		price = cp.Price__c == null ? 0 : cp.Price__c;
       // num = String.valueOf(cp.Quantity__c);
        vmk = autoNextLine(cp.ReagentProducts__r.Vmakefactory__c,10);
        //vmk = autoNextLine('苏州天隆生物科技有限公司',10);
        pzwh = autoNextLine(cp.ReagentProducts__r.NCvpzwh__c,8);
        try {
            zl = Decimal.valueOf(cp.ReagentProducts__r.zl__c); 
        }
        catch (Exception e) {
            zl = 0.0;
        }
        eprice =  zl == 0 ?  null : price / zl ;
        eprice = eprice != null ? eprice.setScale(2) : null ;

        taxrate = pr == null ? null : Integer.valueOf(String.valueOf(pr.Taxrate__c == 17 ? 16 :pr.Taxrate__c ))  ;
        notaxprice = taxrate != null ? price /(1+taxrate/100.0) : price;
       // System.debug('+++'+notaxprice + '\t' + price + '\t' + taxrate +'\t'+ price /(1+taxrate/100.0));
        notaxprice = notaxprice.setScale(2);
        model = autoNextLine(cp.ReagentProducts__r.Model__c,5);
       
        unitprice = pr != null ? pr.MarketPrice__c : null ;
       
        rowHeight = rowh ;
        
        
    	}
    	private String autoNextLine(String s, Integer posLength ){
      if(s == null || s.length() <=posLength ) 
      {
          return s; 
      }
       String temp = '';
              if(s.length() > posLength){
                 for(Integer i = 0; i < s.length(); i++){
                 if(Math.mod(i, posLength ) == 0){
                       if(s.length() > i + posLength){
                         temp += s.substring(i, i + posLength) + '\n'; 
                     }else{ 
                         temp+= s.substring(i,s.length());
                      } 
              }
                 }
              }
          
          return temp;
    }
    }

     
}